<template>
  <div class="page-content">
    <h3 style="margin-bottom: 20px">推广业绩</h3>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane label="推广业绩" name="0"> </el-tab-pane>
      <el-tab-pane label="业绩排行" name="1"> </el-tab-pane>
    </el-tabs>
    <el-form :model="searchForm" ref="searchFormRef" label-width="82px" style="margin-top: 20px">
      <el-row :gutter="25">
        <el-col :span="6">
          <el-form-item label="用户名：" prop="promoterName">
            <el-input v-model="searchForm.promoterName" @blur="getData" placeholder="请输入用户名" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号：" prop="bindPhone">
            <el-input v-model="searchForm.bindPhone" @blur="getData" placeholder="请输入手机号" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="databox">
            <label class="el-form-item__label" style="margin-left: 1.5rem">创建时间：</label>
            <el-date-picker label="创建时间：" v-model="datavalue" type="datetimerange" start-placeholder="开始日期"
              end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
              @change="timeChange" />
          </div>
        </el-col>
      </el-row>
    </el-form>
    <art-table :data="tableData" selection :currentPage="pageNum" :pageSize="pageSize" :total="pagetotal"
      @current-change="currentChange" @size-change="sizeChange" v-if="activeName === '0'">
      <template #default>
        <el-table-column label="订单号" prop="orderNo" />
        <el-table-column label="订单来源" prop="orderSource" align="center" #default="scope">
          {{
            scope.row.orderSource === '0'
              ? '兑换码兑换'
              : scope.row.orderSource === '1'
                ? '新人礼包发放'
                : scope.row.orderSource === '2'
                  ? '老带新'
                  : scope.row.orderSource === '3'
                    ? '线上购买'
                    : ''
          }}
        </el-table-column>
        <el-table-column label="商品名称" prop="productName" align="center" />
        <el-table-column label="下单客户" prop="memberName" align="center">
          <template #default="scope">
            <div>
              <div>姓名：{{ scope.row.memberName }}</div>
              <div>手机号：{{ scope.row.userMobile }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" prop="orderTime" align="center" />
        <el-table-column label="实付金额" prop="orderAmount" align="center" #default="scope">
          {{ scope.row.orderAmount ? (Number(scope.row.orderAmount) / 100).toFixed(2) : '0' }}
        </el-table-column>
        <el-table-column label="推广员昵称" prop="create_time" align="center">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center">
              <div>
                <div>姓名：{{ scope.row.promoterName }}</div>
                <div>手机号：{{ scope.row.bindPhone }}</div>
                <div>级别：{{ scope.row.levelName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="推广员ID" prop="promoterId" align="center" />
        <el-table-column label="收益类型" prop="incomeType" #default="scope" align="center">
          {{
            scope.row.incomeType === 0
              ? '商品佣金'
              : scope.row.incomeType === 1
                ? '邀请人奖励'
                : scope.row.incomeType === 2
                  ? '团队奖励'
                  : scope.row.incomeType === 3
                    ? '活动奖励'
                    : ''
          }}
        </el-table-column>
        <el-table-column label="收益比例" prop="commissionRate" align="center" #default="scope">
          {{ scope.row.commissionRate ? Number(scope.row.commissionRate) / 100 + '%' : '0%' }}
        </el-table-column>
        <el-table-column label="收益" prop="incomeAmount" align="center" #default="scope">
          {{ scope.row.incomeAmount ? (Number(scope.row.incomeAmount) / 100).toFixed(2) : '0' }}
        </el-table-column>
        <el-table-column label="结算方式" prop="settlementType" #default="scope" align="center">
          {{ scope.row.settlementType === 0 ? '自动结算' : '人工结算' }}
        </el-table-column>
        <el-table-column label="结算状态" prop="isSettled" align="center">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.isSettled)">
              {{ buildTagText(scope.row.isSettled) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="结算日期" prop="settledTime" sortable align="center" />
      </template>
    </art-table>
    <art-table :data="tableData" selection :currentPage="pageNum" :pageSize="pageSize" :total="pagetotal"
      @current-change="currentChange" @size-change="sizeChange" v-if="activeName === '1'">
      <template #default>
        <el-table-column label="推广员昵称" prop="promoterName" align="center">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center">
              <img :src="scope.row.avatar" alt="" style="width: 50px; height: 50px; border-radius: 50%"
                v-if="scope.row.avatar" />
              <div style="margin-left: 10px">
                <div>{{ scope.row.promoterName }}</div>
                <div>{{ scope.row.levelName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="推广员ID" prop="promoterId" align="center" />
        <!-- <el-table-column label="账户姓名" prop="realName" align="center" /> -->
        <el-table-column label="申请姓名" prop="promoterName" align="center" />
        <el-table-column label="账户绑定手机号" prop="bindPhone" align="center" />
        <el-table-column label="申请手机号" prop="applyPhone" align="center" />
        <el-table-column label="商品佣金订单数" align="center">
          <template #default="scope">
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                <span>{{
                  Number(scope.row.saleStorePackage) + Number(scope.row.saleVipCard)
                }}</span>
                <el-icon class="el-icon--right"
                  v-if="scope.row.saleStorePackage || scope.row.saleVipCard"><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>班型订单数：{{
                    scope.row.saleStorePackage ? scope.row.saleStorePackage : 0
                    }}</el-dropdown-item>
                  <el-dropdown-item>会员卡订单数：{{
                    scope.row.saleVipCard ? scope.row.saleVipCard : 0
                    }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column label="商品佣金订单金额（元）" align="center">
          <template #default="scope">
            <el-dropdown trigger="click">
              <span class="el-dropdown-link">
                <span>{{
                  (
                    Number(scope.row.saleStorePackageAmount) / 100 +
                    Number(scope.row.saleVipCardAmount) / 100
                  ).toFixed(2)
                }}</span>
                <el-icon class="el-icon--right"
                  v-if="scope.row.saleStorePackageAmount || scope.row.saleVipCardAmount"><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>班型订单金额：{{
                    scope.row.saleStorePackageAmount
                      ? (Number(scope.row.saleStorePackageAmount) / 100).toFixed(2)
                      : 0
                  }}</el-dropdown-item>
                  <el-dropdown-item>会员卡订单金额：{{
                    scope.row.saleVipCardAmount
                      ? (Number(scope.row.saleVipCardAmount) / 100).toFixed(2)
                      : 0
                  }}</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
        <el-table-column label="邀请人奖励订单数" prop="inviterPackageNum" align="center" />
        <el-table-column label="邀请人奖励订单金额（元）" prop="inviterPackageAmount" align="center" />
        <el-table-column label="已结算收益（元）" prop="settledIncome" align="center" #default="scope">
          {{ scope.row.settledIncome ? Number(scope.row.settledIncome) / 100 : 0 }}
        </el-table-column>
      </template>
    </art-table>
  </div>
</template>

<script setup lang="ts">
import { ACCOUNT_TABLE_DATA } from '@/mock/temp/formData'
import { FormInstance } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormRules, TabsPaneContext } from 'element-plus'
import { OrderPageList, getPerformancePage } from '@/api/marketing'

const activeName = ref<string>('0')

const formData = reactive({
  username: '',
  phone: '',
  sex: '',
  dep: ''
})

const columns = reactive([
  { name: '用户名', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '来源', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])

const searchFormRef = ref<FormInstance>()
const searchForm = reactive({
  promoterName: '',
  bindPhone: '',
  queryStartTime: '',
  queryEndTime: ''
})

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const tableData = ref([])

const showDialog = (type: string, row?: any) => {
  if (type === 'edit' && row) {
    formData.username = row.username
    formData.phone = row.mobile
    formData.sex = row.sex === 1 ? '男' : '女'
    formData.dep = row.dep
  } else {
    formData.username = ''
    formData.phone = ''
    formData.sex = '男'
    formData.dep = ''
  }
}
const reset = () => {
  searchForm.promoterName = ''
  searchForm.bindPhone = ''
  searchForm.queryStartTime = ''
  searchForm.queryEndTime = ''
  datavalue.value = ''
}

const getTagType = (status: number) => {
  switch (status) {
    case 1:
      return 'success'
    case 0:
      return 'warning'
  }
}

const buildTagText = (status: number) => {
  let text = ''
  if (status === 0) {
    text = '未结算'
  } else if (status === 1) {
    text = '已结算'
  }
  return text
}

const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}

const datavalue = ref('')
const timeChange = (e: any) => {
  if (e) {
    searchForm.queryStartTime = formatDate(e[0])
    searchForm.queryEndTime = formatDate(e[1])
  } else {
    searchForm.queryStartTime = ''
    searchForm.queryEndTime = ''
  }
  getData()
}
const handleClick = (e: any) => {
  activeName.value = e
  getData()
}

const pagetotal = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const tableLoading = ref(false)

const filterEmptyValues = (obj: any) => {
  const result: any = {}
  for (const key in obj) {
    if (obj[key] !== '' && obj[key] !== null && obj[key] !== undefined) {
      result[key] = obj[key]
    }
  }
  return result
}

const getData = async () => {
  try {
    tableLoading.value = true
    const params = filterEmptyValues(searchForm)
    if (activeName.value === '0') {
      const res = await OrderPageList({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        ...params
      })
      if (res.code === '00000') {
        tableData.value = res.data.list
      }
    } else {
      const res = await getPerformancePage({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        ...params
      })
      if (res.code === '00000') {
        tableData.value = res.data.list
      }
    }
  } catch {
  } finally {
    tableLoading.value = false
  }
}

const currentChange = (val: number) => {
  pageNum.value = val
  getData()
}

const sizeChange = (val: number) => {
  pageSize.value = val
  pageNum.value = 1
  getData()
}

onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.page-content {
  width: 100%;
  height: 100%;

  .user {
    .avatar {
      width: 40px;
      height: 40px;
      border-radius: 6px;
    }

    >div {
      margin-left: 10px;

      .user-name {
        font-weight: 500;
        color: var(--art-text-gray-800);
      }
    }
  }
}
</style>
